<template>
  <div class="min-w-[380px] bg-white rounded-lg shadow p-4 box-border">
    <div ref="chartRef" class="w-full h-full"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import echarts from "@/plugins/echarts";
import type { EChartsType } from "echarts";

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    default: () => ({ normal: 0, faulty: 0, offline: 0, standby: 0 })
  }
});

const chartRef = ref<HTMLElement | null>(null);
let chart: EChartsType | null = null;
let resizeHandler: (() => void) | null = null;

const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value) as unknown as EChartsType;
  updateChart();

  // 保存 resize 处理函数的引用，便于后续清理
  resizeHandler = () => {
    chart?.resize();
    // 窗口大小改变时重新计算布局
    updateChart();
  };

  window.addEventListener("resize", resizeHandler);
};

const updateChart = () => {
  if (!chart || !chartRef.value) return;

  // 获取容器宽度，根据宽度调整饼图位置和大小
  const containerWidth = chartRef.value.clientWidth;

  // 根据容器宽度动态调整饼图的位置和大小
  // 容器越窄，饼图越小且越往左移，为右侧图例留出空间
  let pieCenter, pieRadius;

  if (containerWidth < 400) {
    // 很小的容器
    pieCenter = ["30%", "50%"];
    pieRadius = ["35%", "55%"];
  } else if (containerWidth < 500) {
    // 中小容器
    pieCenter = ["32%", "50%"];
    pieRadius = ["40%", "60%"];
  } else if (containerWidth < 600) {
    // 中等容器
    pieCenter = ["35%", "50%"];
    pieRadius = ["45%", "65%"];
  } else {
    // 大容器
    pieCenter = ["38%", "50%"];
    pieRadius = ["50%", "70%"];
  }

  const option = {
    title: {
      text: "System status",
      left: "left",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold"
      }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      right: "5%",
      top: "center",
      icon: "circle",
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: containerWidth < 450 ? 12 : 14
      },
      formatter: (name: string) => {
        const data = props.chartData[name.toLowerCase()];
        return `${name} ${data}`;
      }
    },
    series: [
      {
        name: "System Status",
        type: "pie",
        center: pieCenter,
        radius: pieRadius,
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: containerWidth < 450 ? 18 : 24,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: props.chartData.normal,
            name: "Normal",
            itemStyle: { color: "#5AD8A6" } // 青色
          },
          {
            value: props.chartData.faulty,
            name: "Faulty",
            itemStyle: { color: "#F46C6C" } // 红色
          },
          {
            value: props.chartData.offline,
            name: "Offline",
            itemStyle: { color: "#909399" } // 灰色
          },
          {
            value: props.chartData.standby,
            name: "Standby",
            itemStyle: { color: "#E6A23C" } // 黄色
          }
        ]
      }
    ]
  };

  chart.setOption(option);
};

// 监听数据变化，更新图表
watch(() => props.chartData, updateChart, { deep: true });

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  // 清理 resize 事件监听器
  if (resizeHandler) {
    window.removeEventListener("resize", resizeHandler);
  }
  // 销毁图表实例
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>
